import axios from "axios";
import {Loading,Message} from "element-ui";
// import router from "@/router/index.js";
import {baseUrl} from "@/setting.js";

let loading;
function startLoading(){
    loading=Loading.service({
        lock:true,
        text:"请求加载中...",
        background:"rgba(0,0,0,0.7)"
    });
}
function endLoading(){
    loading.close();
}

const service=axios.create({
    baseURL:baseUrl,
    timeout:10*1000
});

// 根据特定的key值查询cookie中的value
function getValueCookie(keyName){
    const Cookies=document.cookie;
    const startIndex=Cookies.indexOf(keyName);
    if(startIndex !== -1){
        let startValueIndex=startIndex+(keyName.length+1);
        let endIndex=Cookies.indexOf(";",startValueIndex);
        if(endIndex ===-1){
            endIndex=Cookies.length;
        }
        let value=decodeURI(Cookies.substring(startValueIndex,endIndex));
        return value;
    }else{
        return null;
    }
}

// 请求拦截
service.interceptors.request.use((requestConfig)=>{
    // console.log(requestConfig); //请求配置项
    startLoading();
    requestConfig.headers["cas-token"]=getValueCookie("x-token");
    requestConfig.headers["Content-Type"]="application/json";
    return requestConfig;
},(error)=>{
    return Promise.reject(error);
});

// 响应拦截
service.interceptors.response.use((response)=>{
    // console.log(response); //响应数据体
    endLoading();
    return response.data;
},(error)=>{
    // console.log(error,error.response);
    endLoading();
    if(error.message.includes("timeout")){
        Message.error({
            message:"请求超时",
            center:true
        });
    }
    return Promise.reject(error);
});

export default service;


